package com.cn.ycy.transaction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 演示用的建表语句：
 * <p>
 * CREATE TABLE `account` (
 * `id` int(11) NOT NULL,
 * `name` varchar(50) DEFAULT NULL,
 * `balance` int(255) DEFAULT NULL,
 * PRIMARY KEY (`id`),
 * KEY `idx_balance` (`balance`)
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8
 */
@Component
public class JdbcTempleteDAO {

  Logger logger = LoggerFactory.getLogger(JdbcTempleteDAO.class);

  @Autowired
  JdbcTemplate jdbcTemplate;

  public void insert12() {
    jdbcTemplate.execute("insert into account (id,name) value (12,'事务A');");
  }

  public void select() {
    jdbcTemplate.query("select name from account  where id = 13 ;", new RowMapper<Object>() {
      @Override
      public Object mapRow(ResultSet resultSet, int i) throws SQLException {
        String string = resultSet.getString(1);
        System.out.println(string);
        return null;
      }
    });
  }

  @Transactional(propagation = Propagation.REQUIRED)
  public void insert13() {
    jdbcTemplate.execute("insert into account (id,name) value (13,'事务A');");
  }

  @Transactional(propagation = Propagation.REQUIRED)
  public void insert14() {
    jdbcTemplate.execute("insert into account (id,name) value (14,'事务B');");
  }

  @Transactional(propagation = Propagation.REQUIRED)
  public void insert15() {
    jdbcTemplate.execute("insert into account (id,name) value (15,'事务c');");
  }

  /**
   * 开启一个新事务
   */
  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void insert16() {
    jdbcTemplate.execute("insert into account (id,name) value (16,'事务d');");
  }

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void insert17() {
    jdbcTemplate.execute("insert into account (id,name) value (17,'事务e');");
  }

}
